/*
Designer   : Renyangang

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package logger

import (
	"context"
	"fmt"
	"fpga-vboard/config"
	"os"
	"path"
	"path/filepath"
	rt "runtime"
	"time"

	"github.com/wailsapp/wails/v2/pkg/logger"
	"github.com/wailsapp/wails/v2/pkg/runtime"
)

var Logger *AppLogger
var defaultLogger = logger.NewDefaultLogger()

type MsgType string

const (
	MsgTypeError   MsgType = "error"
	MsgTypeWarn    MsgType = "warn"
	MsgTypeInfo    MsgType = "info"
	MsgTypeSuccess MsgType = "success"
)

type LogEventMsg struct {
	Msgtype MsgType
	Msg     string
}

type AppLogger struct {
	LogLevel   logger.LogLevel
	logPath    string
	loggerFile logger.Logger
	Ctx        context.Context
}

func init() {
	logDir := filepath.Join(config.AppCfg.AppPath, "logs")
	os.MkdirAll(logDir, os.ModePerm)
	logPath := filepath.Join(logDir, config.CurAppParams.LogName)
	loggerFile := logger.NewFileLogger(logPath)
	Logger = &AppLogger{
		LogLevel:   logger.INFO,
		logPath:    logPath,
		loggerFile: loggerFile,
	}
}

func getCallerInfo(skip int) (info string) {
	_, file, lineNo, ok := rt.Caller(skip)
	if !ok {

		info = "runtime.Caller() failed"
		return
	}
	fileName := path.Base(file) // Base函数返回路径的最后一个元素
	now := time.Now()
	// 使用自定义格式字符串格式化时间
	formattedTime := now.Format("2006-01-02 15:04:05")
	return fmt.Sprintf("%s file:%s, line:%d ", formattedTime, fileName, lineNo)
}

func SetLogLevel(level logger.LogLevel) {
	Logger.SetLogLevel(level)
}

func DebugLog(format string, v ...interface{}) {
	Logger.Debug(fmt.Sprintf(format, v...))
}

func InfoLog(format string, v ...interface{}) {
	Logger.Info(fmt.Sprintf(format, v...))
}

func WarningLog(format string, v ...interface{}) {
	Logger.Warning(fmt.Sprintf(format, v...))
}

func ErrorLog(format string, v ...interface{}) {
	Logger.Error(fmt.Sprintf(format, v...))
}

func FatalEvent(format string, v ...interface{}) {
	msg := fmt.Sprintf(format, v...)
	runtime.EventsEmit(Logger.Ctx, "logevent", &LogEventMsg{
		Msgtype: "error",
		Msg:     msg,
	})
	Logger.Error(fmt.Sprintf(format, v...))
}

func FatalLog(format string, v ...interface{}) {
	msg := fmt.Sprintf(format, v...)
	runtime.EventsEmit(Logger.Ctx, "logevent", &LogEventMsg{
		Msgtype: "error",
		Msg:     msg,
	})
	Logger.Fatal(msg)
}

func TraceLog(format string, v ...interface{}) {
	Logger.Trace(fmt.Sprintf(format, v...))
}

func (l *AppLogger) SetLogLevel(level logger.LogLevel) {
	l.LogLevel = level
}

func (l *AppLogger) DebugLog(format string, v ...interface{}) {
	l.Debug(fmt.Sprintf(format, v...))
}

func (l *AppLogger) InfoLog(format string, v ...interface{}) {
	l.Info(fmt.Sprintf(format, v...))
}

func (l *AppLogger) WarningLog(format string, v ...interface{}) {
	l.Warning(fmt.Sprintf(format, v...))
}

func (l *AppLogger) ErrorLog(format string, v ...interface{}) {
	l.Error(fmt.Sprintf(format, v...))
}

func (l *AppLogger) TraceLog(format string, v ...interface{}) {
	l.Trace(fmt.Sprintf(format, v...))
}

func (l *AppLogger) Debug(message string) {
	l.log(logger.DEBUG, message)
}

func (l *AppLogger) Info(message string) {
	l.log(logger.INFO, message)
}

func (l *AppLogger) Warning(message string) {
	l.log(logger.WARNING, message)
}

func (l *AppLogger) Error(message string) {
	l.log(logger.ERROR, message)
}

func (l *AppLogger) Trace(message string) {
	l.log(logger.TRACE, message)
}

func (l *AppLogger) Fatal(message string) {
	defaultLogger.Fatal(message)
	l.loggerFile.Fatal(message)
}

func (l *AppLogger) Print(message string) {
	defaultLogger.Print(message)
	l.loggerFile.Print(message)
}

func (l *AppLogger) log(level logger.LogLevel, message string) {
	info := getCallerInfo(4)
	message = fmt.Sprintf("%s %s", info, message)
	if level >= l.LogLevel {
		switch level {
		case logger.DEBUG:
			l.loggerFile.Debug(message)
			defaultLogger.Debug(message)
		case logger.INFO:
			l.loggerFile.Info(message)
			defaultLogger.Info(message)
		case logger.WARNING:
			l.loggerFile.Warning(message)
			defaultLogger.Warning(message)
		case logger.ERROR:
			l.loggerFile.Error(message)
			defaultLogger.Error(message)
		case logger.TRACE:
			l.loggerFile.Trace(message)
			defaultLogger.Trace(message)
		}
	}
}
